class AccountManager < ActiveRecord::Base
  
  def self.add_money(params)
    if params[:account]&&params[:money]
      account=params[:account]
      money=Integer(params[:money])
    else
      return false
    end
    
    account.account_money +=money
    acc_rcd=AccountRecord.new
    acc_rcd.add_money(:account=>account,:money=>money)
    begin
      Account.transaction do
      account.save!
      acc_rcd.save!
      end
    rescue ActiveRecord::RecordNotSaved
      return false
    else
      return true
    end
  end
  
  #在两个账户之间转账
  def self.transfer(params)
    if params[:sender]&&params[:receiver]&&params[:money]||params[:order]
      #转出账户
      sender=params[:sender]
      #转入账户
      receiver=params[:receiver]
      #转账金额
      money=params[:money]
      #涉及订单
      order=params[:order]
    else 
      return false
    end
    
    if money<=0||sender.account_money<money
      return false
    end
    
    #扣除转出账户金额
    sender.account_money -=money
    #添加转入账户金额
    receiver.account_money +=money
    #记录账户操作
    sender_rcd=AccountRecord.new
    receiver_rcd=AccountRecord.new
    sender_rcd.user_paid(:account=>sender,:money=>money,:order=>order)
    receiver_rcd.admin_income(:account=>receiver,:money=>money,:order=>order)
    #保存
    begin 
        sender.save!
        receiver.save!
        sender_rcd.save!
        receiver_rcd.save!
    rescue ActiveRecord::RecordNotSaved
      return false
    else
      return true
    end
    
    
  end
  
end
